package com.gxpt.app.view;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.shopping_list_Adapter;
import com.gxpt.app.bean.getcartinfo_bean;
import com.gxpt.app.bean.normal;
import com.gxpt.app.bean.upload_bean;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.v24.v_2_4;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.fragment_shopping)
public class Activity_shopping extends BaseActivity {

    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private shopping_list_Adapter mDataAdapter = null;


    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;

    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;


    private View footerView;

    String action  = "";
    String cart_id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);
        initView();

    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){

        if(messageEvent.getMessageType()==Constant.ACTION_to_shopping_add || messageEvent.getMessageType()==Constant.ACTION_to_shopping_reduce){

            cart_id = messageEvent.getData_str();
            action  = messageEvent.getData_ids();

            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
            mCurrentCounter = 0;

            toNet_updatecart();
        }
    }


    @Override
    public void initView() {

        initFooterView();



        mDataAdapter = new shopping_list_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
//        final View header = LayoutInflater.from(this).inflate(R.layout.sample_header,(ViewGroup)findViewById(android.R.id.content), false);
//        mLRecyclerViewAdapter.addFooterView(footerView);


        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mLRecyclerView.setLoadMoreEnabled(false);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
//                if (mCurrentCounter < TOTAL_COUNTER) {
//                    // loading more
//                    requestData();
//                } else {
//                    //the end
//                    mLRecyclerView.setNoMore(true);
//                }
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.addFooterView(footerView);
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    getcartinfo_bean.getcartinfo item = mDataAdapter.getDataList().get(position);


                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private void do_Refresh(){
        page_num = 1;
        toNet_getcartinfo();
    }

    private void do_LoadMore(){
//        page_num += 1;
//        toNet_getcartinfo();
    }

    @Override
    public void initData() {

    }

    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<getcartinfo_bean.getcartinfo> list) {

//        Logger.i("mDataAdapter.getItemCount() = "+mDataAdapter.getItemCount());
        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }



    private void initFooterView(){
        footerView = LayoutInflater.from(context).inflate(R.layout.common_shopping_bar,null, false);
        footerView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,600));
    }


    @Event(value={R.id.toback,R.id.toZhaobiaoModel,R.id.toShenfen,R.id.toPicSel,R.id.toIndusSel,R.id.toAreaSel,R.id.toSure})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toAreaSel:
                Bundle b = new Bundle();
                b.putString("FORM_","Activity_life_need_add");
                jumpActivity(Activity_city_select_2.class,b,false);
                break;
            case R.id.toSure:

                break;
        }
    }



/////NET

    private void toNet_getcartinfo(){
//        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "getcartinfo");

            jsonBody.put("member_id",                AppUtils.get_user_id(context));//二级地区ID
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+"  ["+Constant.URL_getcartinfo+"]");
        HttpUtils.http_post_string(Constant.URL_getcartinfo,jsonBody.toString(),do_getcartinfo);
    }

    //////NET DO

    StringCallback do_getcartinfo = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
            Logger.e(s);
            try{
                getcartinfo_bean data = new Gson().fromJson(s, getcartinfo_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();

                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };


    private void toNet_updatecart(){//+ -
//        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "updatecart");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("cart_id",               cart_id);
            jsonBody.put("action",                action);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+"  ["+Constant.URL_updatecart+"]");
        HttpUtils.http_post_string(Constant.URL_updatecart,jsonBody.toString(),do_updatecart);
    }

    StringCallback do_updatecart = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
//            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    mLRecyclerView.refresh();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };



}
